<template>
  <div>
    <!-- 添加 -->
    <el-button type="primary" icon="el-icon-plus" round @click="addTrademark"
      >添加</el-button
    >
    <!-- 产品列表添加页 -->
    <el-table
      :data="records"
      :header-cell-style="{ color: '#409EFF' }"
      style="width: 100%; margin: 10px 0px"
      border
    >
      <el-table-column
        type="index"
        label="序号"
        width="80px"
        align="center"
      ></el-table-column>
      <el-table-column
        label="品牌名称"
        prop="tmName"
        align="center"
      ></el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" style="width: 200px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            style="margin-right:15px"
            @click="updateTrademark(row)"
            >修改</el-button
          >
           <el-popconfirm title="这是一段内容确定删除吗？" icon="el-icon-delete" icon-color="#409EFF" @onConfirm="deleteTradeMark(row)">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="text-align: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      background
      layout="prev,  pager,next,jumper,->,total,sizes"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
      @current-change="getTradmarkList"
      @size-change="handleSizeChange"
    >
    </el-pagination>

    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
      :before-close="close"
      :show-close="false"
    >
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="mark">
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateTrademark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Trademark",
  data() {
    const validateTmName = (rule, value, callBack) => {
      if (/^[\u4e00-\u9fa5]{2,10}$/.test(value)) {
        callBack();
      } else {
        //不符合条件
        callBack(new Error("品牌名字为2-10位"));
      }
    };
    return {
      page: 1,
      limit: 3,
      //总数据条数
      total: 0,
      //品牌的数据
      records: [],
      dialogFormVisible: false,
      //imageUrl: "",
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "change" },
          { validator: validateTmName, trigger: "change" },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌logo", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getTradmarkList();
  },
  methods: {
    async getTradmarkList(pager = 1) {
      this.page = pager;
      const { page, limit } = this;
      //console.log(this.$ajax.tradmark.reqTrademarkList)
      let result = await this.$ajax.tradmark.reqTrademarkList(page, limit);
      //console.log(result);
      if (result.code == 200) {
        this.total = result.data.total;
        this.records = result.data.records;
      }
    },
    handleSizeChange(limit) {
      this.limit = limit;
      this.getTradmarkList();
    },
    addTrademark() {
      this.dialogFormVisible = true;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },
    cancel() {
      this.dialogFormVisible = false;
      //获取form重置
      this.$refs.mark.resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    saveOrUpdateTrademark() {
      this.$refs.mark.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false;
          try {
            await this.$ajax.tradmark.reqSaveOrUpdate(this.tmForm);
            //弹出提示信息
            this.$message({
              type: "success",
              message: this.tmForm.id ? "修改成功" : "添加成功",
            });
            this.getTradmarkList(this.tmForm.id ? this.page : 1);
            this.$refs.mark.resetFields();
          } catch (error) {
            this.$message({
              type: "danger",
              message: this.tmForm.id ? "修改失败" : "添加失败",
            });
          }
          alert("submit!");
        } else {
          //console.log("error submit!!");
          return false;
        }
      });
    },
    updateTrademark(row) {
      this.dialogFormVisible = true;
      this.tmForm = { ...row };
    },
    close() {},
    async deleteTradeMark({ id }) {
      //整理参数
      //发请求
      try {
        //删除品牌成功
        await this.$ajax.tradmark.reqDeleteTrademark(id);
        //再次获取品牌数据
        //this.recores:当前table展示品牌的数据（数组）
        this.getTradmarkList(
          this.records.length > 1 ? this.page : this.page - 1
        );
      } catch (error) {
        //删除失败
        this.$message({
          type: "error",
          message: "删除失败",
        });
      }
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>